//
//  LXPageCollectionViewLayout.swift
//  LXPageView
//
//  Created by seven on 2017/12/22.
//  Copyright © 2017年 seven. All rights reserved.
//

import UIKit

class LXPageCollectionViewLayout: UICollectionViewFlowLayout {
    var cols: Int = 4
    var rows: Int = 2
    private lazy var cellAttrs: [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
    private lazy var maxWidth: CGFloat = 0
}

//MARK:- 准备布局
extension LXPageCollectionViewLayout{
    override func prepare() {
        super.prepare()
        //0.计算宽度和高度
        let itemW = (collectionView!.bounds.width - sectionInset.left - sectionInset.right - CGFloat(cols - 1) * minimumInteritemSpacing) / CGFloat(cols)
        let itemH = (collectionView!.bounds.height - sectionInset.top - sectionInset.bottom - CGFloat(rows - 1) * minimumLineSpacing) / CGFloat(rows)
        //1.获取一共多少组
        let sectionCount = collectionView!.numberOfSections
        //3.获取每组中有多少item
        var prePageCount: Int = 0
        
        for i in 0..<sectionCount{
            let itemCount = collectionView!.numberOfItems(inSection: i)
            
            for j in 0..<itemCount{
                //2.1获取cell对应的indexPath
                let indexPath = IndexPath(item: j, section: i)
                //2.2根据indexPath创建collectionViewLayoutAttributes
                let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
                //2.3计算J在改组中的几页
                let page = j / (cols * rows)
                let index = j % (cols * rows)
                //2.4设置attribute的frame
                let itemY = sectionInset.top + CGFloat(index / cols) * (itemH + minimumLineSpacing)
                let itemX = CGFloat(prePageCount + page) * collectionView!.bounds.width + sectionInset.left + (itemW + minimumInteritemSpacing) * CGFloat(index % cols)
                attr.frame = CGRect(x: itemX, y: itemY, width: itemW, height: itemH)
                cellAttrs.append(attr)
            }
            prePageCount += (itemCount - 1) / (cols * rows) + 1
        }
        //3.计算最大Y值
        maxWidth = CGFloat(prePageCount) * collectionView!.bounds.width
    }
}

//MARK:- 返回布局
extension LXPageCollectionViewLayout{
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return cellAttrs
    }
}

//MARK:- 返回collectionView内容高度
extension LXPageCollectionViewLayout{
    override var collectionViewContentSize: CGSize{
        return CGSize(width: maxWidth, height: 0)
    }
}
